import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import '../entity/content_submission.dart';

/// 媒体处理工具类
class MediaProcessor {
  static final MediaProcessor _instance = MediaProcessor._internal();

  factory MediaProcessor() {
    return _instance;
  }

  MediaProcessor._internal();

  /// 获取应用文档目录
  Future<Directory> get _documentsDirectory async {
    return await getApplicationDocumentsDirectory();
  }

  /// 获取媒体存储目录
  Future<Directory> get _mediaDirectory async {
    final docs = await _documentsDirectory;
    final mediaDir = Directory(path.join(docs.path, 'media_assets'));
    if (!await mediaDir.exists()) {
      await mediaDir.create(recursive: true);
    }
    return mediaDir;
  }

  /// 获取缩略图存储目录
  Future<Directory> get _thumbnailDirectory async {
    final docs = await _documentsDirectory;
    final thumbDir = Directory(path.join(docs.path, 'thumbnails'));
    if (!await thumbDir.exists()) {
      await thumbDir.create(recursive: true);
    }
    return thumbDir;
  }

  /// 复制图片到本地存储
  Future<String> processImageAsset(String sourcePath) async {
    try {
      final sourceFile = File(sourcePath);
      if (!await sourceFile.exists()) {
        throw Exception('Source image file does not exist');
      }

      final mediaDir = await _mediaDirectory;
      final fileName =
          'img_${DateTime.now().millisecondsSinceEpoch}${path.extension(sourcePath)}';
      final targetPath = path.join(mediaDir.path, fileName);

      await sourceFile.copy(targetPath);
      return targetPath;
    } catch (e) {
      throw Exception('Failed to process image: $e');
    }
  }

  /// 复制视频到本地存储并生成缩略图
  Future<Map<String, String>> processVideoAsset(String sourcePath) async {
    try {
      final sourceFile = File(sourcePath);
      if (!await sourceFile.exists()) {
        throw Exception('Source video file does not exist');
      }

      // 复制视频文件
      final mediaDir = await _mediaDirectory;
      final videoFileName =
          'vid_${DateTime.now().millisecondsSinceEpoch}${path.extension(sourcePath)}';
      final videoTargetPath = path.join(mediaDir.path, videoFileName);
      await sourceFile.copy(videoTargetPath);

      // 生成缩略图
      final thumbnailPath = await _generateVideoThumbnail(videoTargetPath);

      return {'videoPath': videoTargetPath, 'thumbnailPath': thumbnailPath};
    } catch (e) {
      throw Exception('Failed to process video: $e');
    }
  }

  /// 生成视频缩略图
  Future<String> _generateVideoThumbnail(String videoPath) async {
    try {
      final thumbDir = await _thumbnailDirectory;
      final fileName = 'thumb_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final thumbnailPath = path.join(thumbDir.path, fileName);

      // 这里应该使用视频处理库来生成真实的缩略图
      // 为了演示，我们创建一个占位符文件
      await _createPlaceholderThumbnail(thumbnailPath);

      return thumbnailPath;
    } catch (e) {
      throw Exception('Failed to generate thumbnail: $e');
    }
  }

  /// 创建占位符缩略图
  Future<void> _createPlaceholderThumbnail(String thumbnailPath) async {
    try {
      // 从 assets 中复制一个默认的缩略图图片
      // 使用 share1.png 作为视频缩略图的占位符
      final ByteData data = await rootBundle.load('assets/images/share1.png');
      final List<int> bytes = data.buffer.asUint8List();

      final file = File(thumbnailPath);
      await file.writeAsBytes(bytes);
    } catch (e) {
      // 如果复制失败，创建一个最小的透明 PNG
      final file = File(thumbnailPath);
      // 创建一个 1x1 透明 PNG 的字节数据
      final pngBytes = [
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG 签名
        0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, // IHDR 块
        0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, // 1x1 像素
        0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, // RGBA, 无压缩
        0x89, 0x00, 0x00, 0x00, 0x0B, 0x49, 0x44, 0x41, // IDAT 块
        0x54, 0x08, 0x1D, 0x01, 0x00, 0x00, 0x00, 0x00, // 透明像素数据
        0x00, 0x37, 0x6E, 0xF9, 0x24, 0x00, 0x00, 0x00, // 结束
        0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, // IEND
      ];
      await file.writeAsBytes(pngBytes);
    }
  }

  /// 批量处理图片资源
  Future<List<MediaAsset>> processImageCollection(
    List<String> imagePaths,
  ) async {
    final List<MediaAsset> assets = [];

    for (int i = 0; i < imagePaths.length; i++) {
      try {
        final localPath = await processImageAsset(imagePaths[i]);
        final asset = MediaAsset(
          assetId: 'img_${DateTime.now().millisecondsSinceEpoch}_$i',
          localPath: localPath,
          mediaType: ContentMediaType.imageCollection,
          uploadedAt: DateTime.now(),
        );
        assets.add(asset);
      } catch (e) {
        // 记录错误但继续处理其他图片
        print('Failed to process image ${imagePaths[i]}: $e');
      }
    }

    return assets;
  }

  /// 处理视频资源
  Future<MediaAsset> processVideoClip(String videoPath) async {
    try {
      final result = await processVideoAsset(videoPath);

      return MediaAsset(
        assetId: 'vid_${DateTime.now().millisecondsSinceEpoch}',
        localPath: result['videoPath']!,
        mediaType: ContentMediaType.videoClip,
        thumbnailPath: result['thumbnailPath'],
        uploadedAt: DateTime.now(),
      );
    } catch (e) {
      throw Exception('Failed to process video clip: $e');
    }
  }

  /// 删除媒体文件
  Future<bool> removeMediaAsset(MediaAsset asset) async {
    try {
      final file = File(asset.localPath);
      if (await file.exists()) {
        await file.delete();
      }

      // 如果有缩略图，也删除
      if (asset.thumbnailPath != null) {
        final thumbFile = File(asset.thumbnailPath!);
        if (await thumbFile.exists()) {
          await thumbFile.delete();
        }
      }

      return true;
    } catch (e) {
      print('Failed to remove media asset: $e');
      return false;
    }
  }

  /// 清理过期的媒体文件
  Future<void> cleanupExpiredAssets({int daysToKeep = 30}) async {
    try {
      final mediaDir = await _mediaDirectory;
      final thumbDir = await _thumbnailDirectory;
      final cutoffDate = DateTime.now().subtract(Duration(days: daysToKeep));

      await _cleanupDirectory(mediaDir, cutoffDate);
      await _cleanupDirectory(thumbDir, cutoffDate);
    } catch (e) {
      print('Failed to cleanup expired assets: $e');
    }
  }

  /// 清理目录中的过期文件
  Future<void> _cleanupDirectory(
    Directory directory,
    DateTime cutoffDate,
  ) async {
    if (!await directory.exists()) return;

    await for (final entity in directory.list()) {
      if (entity is File) {
        final stat = await entity.stat();
        if (stat.modified.isBefore(cutoffDate)) {
          try {
            await entity.delete();
          } catch (e) {
            print('Failed to delete file ${entity.path}: $e');
          }
        }
      }
    }
  }

  /// 获取媒体文件大小
  Future<int> getAssetSize(MediaAsset asset) async {
    try {
      final file = File(asset.localPath);
      if (await file.exists()) {
        return await file.length();
      }
      return 0;
    } catch (e) {
      return 0;
    }
  }

  /// 验证媒体文件是否存在
  Future<bool> validateAsset(MediaAsset asset) async {
    try {
      final file = File(asset.localPath);
      return await file.exists();
    } catch (e) {
      return false;
    }
  }
}
